package com.estock.crawler.parse;

import java.io.File;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.estock.common.util.FileUtil;
import com.estock.common.util.StockUtil;
import com.estock.crawler.utils.ESCrawlerUtil;
import com.estock.crawler.writer.AbstractJqkaStockCsvWriter;

public abstract class AbstractJqkaStockParser {
	
	private static final Logger logger = LoggerFactory.getLogger(AbstractJqkaStockParser.class);
	
	public void parse() {
		// delete csv file first
		ESCrawlerUtil.deleteFile(ESCrawlerUtil.get10jqkaCsvDir() + getCsvFilename());
		
		for (File file : getAllFilesToBeParsed()) {
			logger.info("Start parsing file: " + file.getAbsolutePath());
			parseHtml(file);
		}
	}
	
	private void parseHtml(File file) {
		String stockcode = getStockCodeFromFile(file);
		if (!StockUtil.isAStock(stockcode)) {
			logger.info("interupt parsing because it is not A type! code= " + stockcode);
			return;
		}
		
		Document doc = Jsoup.parse(
				FileUtil.readString(file.getAbsolutePath(), "GBK"));
		
		getJqkaStockCsvWriter(stockcode, doc).write();
	}
	
	public abstract List<File> getAllFilesToBeParsed();

	public abstract AbstractJqkaStockCsvWriter getJqkaStockCsvWriter(
			String stockcode, Document doc);

	public abstract String getStockCodeFromFile(File file);
	
	public abstract String getCsvFilename();

}
